package com.study.banyiyi.util;

import com.mysql.cj.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName FilesUtil
 * @Description 文件上传下载工具类
 * @Author yangwm
 * @Date 2021/6/28 15:34
 * @Version 1.0
 */
public class FilesUtil {


    /*常见文件类型，使用字符流进行处理*/
    static List<String> fileTypeList= Arrays.asList("txt");

    /**
     * 单文件上传
     * @param file 文件信息
     * @param path 文件存放路径（即上传服务器存放文件地址）
     * @return
     */
    public static ResultMsg simpleUploadFile(MultipartFile file,String path) throws IOException {
        /*1、判断文件内容是否为空*/
        long size = file.getSize();
        if(size <= 0){
            return new ResultMsg("204","上传文件内容为空！");
        }
        /*2、获取文件类型*/
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".")+1);

        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        /*3、判断输出文件路径是否存在，存在则直接替换，不存在则直接创建文件夹*/
        if(path.isEmpty()){
            return new ResultMsg("204","输出文件地址为空！");
        }else if(!new File(path).exists() || !new File(path).isDirectory()){
            new File(path).mkdirs();
        }
        /*4、判断类型属于字符型的用字符流、属于字节型的用字节流*/
        if(fileTypeList.contains(fileType)){
            try {
                bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream(),"utf-8"));
                bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path+"/"+file.getOriginalFilename())),"utf-8"));
                /*5、输入流读取数据并传输到输出流保存到对应文件地址*/
                if(!bufferedReader.ready()){
                    System.out.println("字符流暂时无法读取！");
                    return new ResultMsg("500","字符流暂时无法读取!");
                }
                char[] buff = new char[1024];
                int len = 0;
                while ((len = bufferedReader.read(buff)) != -1){
                    bufferedWriter.write(buff,0,len);
                    System.out.println(new String(new String(buff,0,len).getBytes(),"utf-8"));
                }
                return new ResultMsg("200","文件上传成功！");
            } catch (IOException e) {
                e.printStackTrace();
                return new ResultMsg("500","文件上传失败！");
            } finally {
                bufferedWriter.close();
                bufferedReader.close();
            }
        }else {
            try {
                bufferedInputStream = new BufferedInputStream(file.getInputStream());
                bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File(path+"/"+file.getOriginalFilename())));
                /*6、字节流读取文件内容传输到输出流保存到对应地址*/
                byte[] buff = new byte[1024];
                int len = 0;
                while ((len = bufferedInputStream.read(buff)) != -1){
                    bufferedOutputStream.write(buff,0,len);
                }
                return new ResultMsg("200","文件上传成功！");
            } catch (IOException e) {
                e.printStackTrace();
                return new ResultMsg("500","文件上传失败！");
            } finally {
                bufferedOutputStream.close();
                bufferedInputStream.close();
            }

        }

    }

    /**
     * 根据文件地址进行将文件传输到浏览器进行下载操作
     * @param path 文件存放地址
     * @param fileName  文件名称
     * @return
     */
    public static  ResultMsg simpleDownloadData(String path,String fileName) throws IOException {
        /*1、首先判断地址信息是否为空*/
        if(StringUtils.isNullOrEmpty(path)){
            return new ResultMsg("204","下载文件路径为空！");
        }
        /*2、判断文件是否存在*/
        if(!new File(path).exists()){
            return new ResultMsg("204","输出文件地址为空！");
        }else {
            /*3、直接使用字节流读取并输出到浏览器实现在线下载的功能*/
            BufferedInputStream bufferedInputStream = null;
            BufferedOutputStream bufferedOutputStream = null;
            /*4、因为是要直接输出流到浏览器，所以我们在此还需要获取浏览器的输出流*/
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = attributes.getResponse();
            try{
                bufferedInputStream = new BufferedInputStream(new FileInputStream(new File(path)));
                bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
                int len = 0;
                byte[] buff = new byte[1024];
                //清空response
                response.reset();
                //设置请求头，并转换编码格式
                fileName = new String(fileName.getBytes(),"ISO8859-1");
                response.addHeader("Content-Disposition","attachment;filename="+fileName);
                response.addHeader("Content-Length",""+new File(path).length());
                response.setContentType("application/octet-stream");
                //*5、读取流信息并写入到浏览器*/
                while ((len = bufferedInputStream.read(buff)) != -1){
                    bufferedOutputStream.write(buff,0,len);
                }
                return new ResultMsg("200","文件下载成功！");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return new ResultMsg("500","文件下载失败！");
            } catch (IOException e) {
                e.printStackTrace();
                return new ResultMsg("500","文件下载失败！");
            }finally {
                bufferedOutputStream.flush();
                bufferedOutputStream.close();
                bufferedInputStream.close();
            }
        }
    }
}
